package com.cn.file;

import ch.qos.logback.core.util.FileUtil;

import javax.script.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: chenyuncong
 * @Date: 2020/3/23 15:12
 * yH8nVCzwnol9usVVPrlHGgdB
 */
public class DowloadJSUtil {

    public static void main(String[] args) throws Exception {
//        String html = getHtmlContentS("http://api.map.baidu.com/api?v=2.0&ak=?");
//        html = html.substring(html.indexOf("src="));
//        html = html.substring(html.indexOf("\"") + 1, html.lastIndexOf("\""));
//        String jsCon = getHtmlContentS(html);
//        System.out.println(jsCon);
//        createFile("F:\\baiduMap.js",jsCon);

        toJs("F:\\baiduMap.js");
    }

    public static void toJs(String path) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript" );
        Bindings bind = engine.createBindings();
        bind.put( "factor", 0);
        engine.setBindings(bind, ScriptContext. ENGINE_SCOPE);

        int first = 23;
        int second = 7;

        System. out.println("输入的参数是：" + first + ", " + second);
        engine.eval( new FileReader(path ));

        if (engine instanceof Invocable) {
            Invocable in = (Invocable) engine;
            // 执行js函数
            Double result = (Double) in.invokeFunction( "window.BMap.Point", first, second);
            System. out.println("运算结果是：" + result.intValue());
        }
    }

    public static String getHtmlContent(URL url) {
        StringBuffer contentBuffer = new StringBuffer();

        int responseCode = -1;
        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");// IE代理进行下载
            con.setConnectTimeout(60000);
            con.setReadTimeout(60000);
            // 获得网页返回信息码
            responseCode = con.getResponseCode();
            if (responseCode == -1) {
                String re = url.toString() + " : connection is failure...";
                con.disconnect();
                return re;
            }
            if (responseCode >= 400) // 请求失败
            {
                String re = "请求失败:get response code: " + responseCode;
                con.disconnect();
                return re;
            }
            InputStream inStr = con.getInputStream();
            InputStreamReader istreamReader = new InputStreamReader(inStr, "UTF-8");
            BufferedReader buffStr = new BufferedReader(istreamReader);

            String str = null;
            while ((str = buffStr.readLine()) != null)
                contentBuffer.append(str).append("\r\n");
            inStr.close();
        } catch (IOException e) {
            e.printStackTrace();
            contentBuffer = null;
            System.out.println("error: " + url.toString());
        } finally {
            con.disconnect();
        }
        return contentBuffer.toString();
    }

    /**
     * 获取js内容
     *
     * @param url
     * @return
     */
    public static String getHtmlContentS(String url) {
        if (!url.toLowerCase().startsWith("http://")) {
            url = "http://" + url;
        }
        try {
            URL rUrl = new URL(url);
            return getHtmlContent(rUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return "网址错误！";
        }

    }

    /**
     * 获取到js内容生成一个对应js文件
     *
     * @param url
     * @return
     */
    public static boolean mkDirFile(URL url, File file) {
        boolean isSuccess = false;
        String htmlContent = "";
        try {
            htmlContent = getHtmlContent(url);
//　　　　　　　　下载到一个js文件中，需要之前创建一个js文件
            isSuccess = createFile("", htmlContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isSuccess;
    }

    public static boolean createFile(String fileName, String filecontent) {
        Boolean bool = false;
        String filenameTemp = fileName ;//文件路径+名称+文件类型
        File file = new File(filenameTemp);
        try {
            //如果文件不存在，则创建新的文件
            if (!file.exists()) {
                file.createNewFile();
                bool = true;
                System.out.println("success create file,the file is " + filenameTemp);
                //创建文件成功后，写入内容到文件里
                writeFileContent(filenameTemp, filecontent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }

    public static boolean writeFileContent(String filepath, String newstr) throws IOException {
        Boolean bool = false;
        String filein = newstr + "\r\n";//新写入的行，换行
        String temp = "";

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            File file = new File(filepath);//文件路径(包括文件名称)
            //将文件读入输入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();

            //文件原有内容
            for (int i = 0; (temp = br.readLine()) != null; i++) {
                buffer.append(temp);
                // 行与行之间的分隔符 相当于“\n”
                buffer = buffer.append(System.getProperty("line.separator"));
            }
            buffer.append(filein);

            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buffer.toString().toCharArray());
            pw.flush();
            bool = true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            //不要忘记关闭
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return bool;
    }
}
